﻿using ConfExpert.Utility;
using DevExpress.XtraBars;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Base;
using DevTeam;
using Extensions;
using SpreadsheetGear;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Windows.Forms;

namespace ConfOrder
{
    public partial class ImportBreakdown : XPopupForm
    {
        DataTable dtSource = null;
        public ImportBreakdown()
        {
            ReadFile();

            if (dtSource == null)
                return;

            InitializeComponent();
        }

        private void ReadFile()
        {
            using (OpenFileDialog ofd = new OpenFileDialog())
            {
                ofd.Filter = "Excel Files|*.xlsx";
                DialogResult dr = ofd.ShowDialog();
                if (dr == DialogResult.OK)
                {
                    FileInfo fi = new FileInfo(ofd.FileName);

                    IWorkbook Workbook = SpreadsheetGear.Factory.GetWorkbook(fi.FullName);
                    DataSet ds = Workbook.GetDataSet(SpreadsheetGear.Data.GetDataFlags.None | SpreadsheetGear.Data.GetDataFlags.NoColumnTypes);
                    dtSource = ds.Tables[0].DefaultView.ToTable(false, "zoekcode", "m1", "m2", "m3", "m4", "m5", "m6", "m7", "m8", "m9", "m10", "m11", "m12", "m13", "m14", "m15", "naam", "L_plaats", "L_land", "fixdatum", "klantnr", "prev");
                }
            }
        }


        private void ImportBreakdown_Load(object sender, EventArgs e)
        {
            MainToolbar.Visible = true;

            gv.Init(dtSource);

            gleBreakdown.EditValueChanged += gleBreakdown_EditValueChanged;
            gleBreakdown.Properties.Assign(RepositoryManager.riDagilim);
            gv.BestFitColumns();
        }

        DataTable dtSize;
        private void gleBreakdown_EditValueChanged(object sender, EventArgs e)
        {
            int dagilimId = gleBreakdown.EditValue.ToIntNN();

            dtSize = AppSession.DataManager.ExecuteDataTable("COGetDagilimVertical", dagilimId);
            dtSize.Columns.Add("M", typeof(int));
            for (int i = 0; i < dtSize.Rows.Count; i++)
            {
                dtSize.Rows[i]["M"] = i + 1;
            }
            gvEsleme.Init(dtSize);
            gvEsleme.MakeColumnInvisible("Name");

            gvEsleme.Columns["Size"].OptionsColumn.AllowEdit = false;

            Esle();
        }

        private void gvEsleme_CellValueChanged(object sender, CellValueChangedEventArgs e)
        {
            Esle();
        }

        List<string> Esleme = new List<string>();

        private void Esle()
        {
            gvEsleme.CloseEditor();
            gvEsleme.UpdateCurrentRow();

            Esleme = new List<string>();

            DataTable dtEsleme = gvEsleme.DataTable();

            for (int i = 1; i < 16; i++)
            {
                string colName = "m" + i.ToString();

                DataRow[] drs = dtEsleme.Select("M = " + i);
                string name = "NA";

                if (drs.Length > 0)
                {
                    name = drs[0]["Size"].ToString();

                    Esleme.Add(colName + ":" + drs[0]["Name"].ToString());
                }

                gv.SetCaptions(colName + ":" + name);
            }
            gv.BestFitColumns();
        }

        private void btnKaydet_ItemClick(object sender, ItemClickEventArgs e)
        {
            DataTable dtr = gv.DataTable().Copy();
            foreach (string pair in Esleme)
            {
                string[] pairs = pair.Split(":".ToCharArray());
                dtr.Columns[pairs[0]].ColumnName = pairs[1];
            }

            dtr.TableName = "Breakdown";

            string xml = dtr.Serialize();
            xml = xml.Replace("'", "''");
            int dagilimId = gleBreakdown.EditValue.ToIntNN();

            DataTable dtSonuc = AppSession.DataManager.ExecuteDataTable("COInsBreakdown", xml, dagilimId);
            if (dtSonuc.Rows.Count > 0)
            {
                string firstRow = dtSonuc.Rows[0][0].ToStringNN();
                if (firstRow.ToLower().StartsWith("error:"))
                    XtraMessageBox.Show(firstRow, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                MessageBox.Show("The file is successfully imported!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.DialogResult = DialogResult.OK;
            }
        }
    }
}